package com.cdqidi.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cdqidi.entity.User;
import com.cdqidi.interceptor.IpAuthInterceptor;
import com.cdqidi.interceptor.WxVerInterceptor;
import com.cdqidi.service.AuthService;
import com.cdqidi.util.RedisMgr;
import com.cdqidi.util.StaticResource;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.kit.HttpKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.utils.JsonUtils;
public class AuthController extends Controller{
	private final static String GETCAPTCHAURL=StaticResource.URL+"/weiXinManager/api/captcha";
	private final static String AUTHURL=StaticResource.URL+"/weiXinManager/security?gCode=xzd&isAuthorize=3&rUrl=";
	private final static String SECURITYURL=StaticResource.URL+"/weiXinManager/security?wxorgid=";
	private final static String PAYURL=StaticResource.URL+"/wPay/pay/";
	private static Logger logger = Logger.getLogger(AuthController.class);
	public void test() {
		String string = HttpKit.get(StaticResource.URL+"/wPay/auth/getCode?cid=xzd");
		ApiResult result = new ApiResult(string);
		String code = result.getStr("code");
		setAttr("code", code);
		
		JSONObject json = new JSONObject();
		json.put("schoolid","604830");
		json.put("parid","852304543819524514485415632");
		json.put("stuid","849757776817931979089844858");
		json.put("openid","oKF4jwP2wz6CGwjWZgcGXVa1r79o");
		json.put("wxorgid","e38e92f3-76df-43a7-9ef5-461733ce3180");
		json.put("mobile","13668266758");
		json.put("chargeCode","ZFCS_001");
		json.put("month","1");
		json.put("delChargeCode", "xzdtytc");
		
		try {
			json.put("url",URLEncoder.encode("http://www.baidu.com","UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		logger.info(json.toJSONString());
		setAttr("json", json.toJSONString());
		
		render("/WEB-INF/page/test.jsp");
	}
	
	
	@Before({GET.class,IpAuthInterceptor.class})
	public void getCode() {
		String cid = getPara("cid");
		JSONObject json = new JSONObject(true);
		AuthService.getInstance().getCode(json,cid);
		logger.info("返回code: "+json);
		renderJson(json);
	}
	
	@Before({GET.class,WxVerInterceptor.class})
	public void xzdAuthorize() {
		String cid = getPara("cid");
		String code = getPara("code");
		String param = getPara("param");
		logger.info("cid: "+cid);
		logger.info("code: "+code);
		logger.info("param: "+param);
		JSONObject jo = new JSONObject();
		User user = new User();
		HttpSession session = getSession();
		AuthService.getInstance().xzdAuthorize(cid,code, param,jo,user, session);
		String url="";
		if(jo.getInteger("errcode")==0) {
			url = StaticResource.URL+"/wPay/pay/unifiedOrder?wxorgid="+jo.getString("errmsg");
			try {
				url=AUTHURL+URLEncoder.encode(url,"UTF-8");
				getResponse().sendRedirect(url);
				renderNull();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else {
			setAttr("errmsg", jo.getString("errmsg"));
			url="/WEB-INF/page/error/500.jsp";
			render(url);
		}
	}
	
	@Before(GET.class)
	public void authorize() {
		String code = getPara("code");
		String cid = getPara("cid");
		String param = getPara("param");
		JSONObject jo = new JSONObject();
		AuthService.getInstance().authorize(cid,code, param,jo, this);
		String url="";
		if(jo.getInteger("errcode")==0) {
			url="/WEB-INF/page/order.jsp";
		}else {
			setAttr("errmsg", jo.getString("errmsg"));
			url="/WEB-INF/page/error/500.jsp";
		}
		render(url);
	}
	
	public void isYzm() {
		String mobile = getPara("parMobile");
		String mobileVal = getPara("mobileVal");
		String chargeCode = getPara("chargeCode");
		String month = getPara("month");
		
		JSONObject json = new JSONObject();
		AuthService.getInstance().isYzm(mobile, mobileVal, chargeCode,month,this, json);
		System.out.println("json");
		
		renderJson(json);
	}
	
	
	public void forwardOrder() {
		try {
			String id = getSessionAttr("wPay_user");
			String json = RedisMgr.getInstance().getProp(id);
			if(StringUtils.isEmpty(json)) {
				setAttr("errmsg", "会话超时，请重新进入购买页面");
				render("/WEB-INF/page/order.jsp");
				return;
			}
			User user = JSON.parseObject(json, User.class);
			if(null==user) {
				setAttr("errmsg", "会话超时，请重新进入购买页面");
				render("/WEB-INF/page/order.jsp");
				return;
			}
			String wxorgid = user.getWxorgid();
			if(StringUtils.isEmpty(wxorgid)) {
				setAttr("errmsg", "会话超时，请重新进入购买页面");
				render("/WEB-INF/page/order.jsp");
				return;
			}
			String url=SECURITYURL+wxorgid+"&isAuthorize=3&rUrl=";
			url+=URLEncoder.encode(PAYURL,"UTF-8");
			System.out.println(url);
			getResponse().sendRedirect(url);
			renderNull();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 发送验证码
	 */
	public void sendYzm() {
		String id = getSessionAttr("wPay_user");
		String url="/WEB-INF/page/error/500.jsp";
		try {
			if(StringUtils.isEmpty(id)) {
				setAttr("errmsg", "会话超时，请重新进入购买页面");
				render(url);
				return;
			}
			String json = RedisMgr.getInstance().getProp(id);
			if(StringUtils.isEmpty(json)) {
				setAttr("errmsg", "会话超时，请重新进入购买页面");
				render(url);
				return;
			}
			System.out.println("json: "+json);
			User user = JSON.parseObject(json, User.class);
			Map<String,String> map = new HashMap<String, String>();
			map.put("cid", StaticResource.CID);
			map.put("mobile",user.getMobile());
			map.put("type","wx_pay");
			map.put("wxorgid", user.getWxorgid());
			map.put("openid", user.getOpenid());
			String string = HttpKit.post(GETCAPTCHAURL, JsonUtils.toJson(map));
			System.out.println(string);
			renderJson(string);
			return;
		} catch (ClassNotFoundException | IOException e) {
			setAttr("errmsg", "系统错误");
			render(url);
			return;
		}
	}
}